<script lang="ts" setup>
import { CellGroup, Field, showFailToast, showSuccessToast } from 'vant'
import { ContactApi } from '~/api/ContactApi'
import StrPropertyEdit from '~/components/common/StrPropertyEdit.vue'
import type { ContactModel } from '~/model'

const route = useRoute()
const router = useRouter()

const id = ref(-1)
const contact = ref(null as ContactModel | null)

onMounted(async () => {
  const _id = route.query.id as (string | undefined)
  if (!_id) {
    return
  }
  id.value = Number.parseInt(_id)
  const allContact = await ContactApi.getAll()
  contact.value = allContact.find(x => x.id === id.value) || null

  // console.log(contact.value)
})

function handleCancle() {
  router.back()
}

async function handleSave() {
  if (contact.value === null)
    return

  const id = contact.value.id

  const success = await ContactApi.update(id, contact.value)
  if (success) {
    showSuccessToast('保存成功')
    setTimeout(() => {
      router.back()
    }, 1000)
  }
  else {
    showFailToast('保存失败，请联系管理员')
  }
}
</script>

<template>
  <div v-if="contact" of-auto>
    <ContactAvatar
      :contact="contact"
      :size="32"
      :can-click="true"
      :can-unload="true"
      mx-auto my2
    />

    <StrPropertyEdit
      :obj="contact" :properties="[
        ['单位/姓名', 'name'],
        ['联系电话', 'phone'],
      ]"
    />

    <div p4>
      档案
    </div>

    <CellGroup>
      <Field
        v-model="contact.notes"
        placeholder="暂无档案"
        type="textarea"
        :autosize="true"
      />
    </CellGroup>

    <div flex p4>
      <LxButton
        title="取消"
        icon="xmark"
        color="grey"
        :action="handleCancle"
      />
      <LxButton
        icon="check"
        title="确定"
        :action="handleSave"
      />
    </div>
  </div>
</template>

<route lang="yaml">
meta:
  title: 编辑联系人
</route>
